package cn.tedu.web.service.impl;

import java.util.List;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import cn.tedu.web.entity.Administrator;
import cn.tedu.web.mapper.AdministratorMapper;
import cn.tedu.web.service.IAdministratorService;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author issen
 * @since 2021-09-13
 */
@Service
public class AdministratorServiceImpl extends ServiceImpl<AdministratorMapper, Administrator>
		implements IAdministratorService {
	@Autowired
	private AdministratorMapper administratorMapper;

	/**
	 * 后台管理员登录处理函数
	 * 
	 * @param username
	 * @param password
	 */
	public Long login(String username, String password) {
		// 检测用户名的存在性
		Boolean exists = administratorMapper.exists(username);
		if (!Boolean.TRUE.equals(exists)) {
			throw new RuntimeException("用户名不存在!");
		}
		// 检测用户的密码是否正确, 如果账号密码匹配，则返回账号的ID
		return administratorMapper.checkUsernameAndPassword(username, password);
	}

	public List<Administrator> pageList(int pageNum, int pageSize) {
		return administratorMapper.pageList(new Page<>()).getRecords();
	}

	/**
	 * 新增管理员账号
	 */
	public Integer insert(Administrator administrator) {
		if (administrator == null) {
			return 0;
		}
		if(StringUtils.isAnyBlank(administrator.getUsername(), administrator.getPassword())) {
			// 如果用户名或者密码，存在空的情况下，返回零
			return 0;
		}
		// 检查账号是否存在
		Boolean exists = administratorMapper.exists(administrator.getUsername());
		if(Boolean.TRUE.equals(exists)) {
			return -1;
		}
		return administratorMapper.insert(administrator);
	}

	/**
	 * 删除账户
	 */
	public Integer delete(Long id) {
		if (id == null || id < 1) {
			return 0;
		}
		return administratorMapper.softDelete(id);
	}

	/**
	 * 启用账号
	 */
	public Integer enable(Long id) {
		if(id == null || id < 1) {
			return 0;
		}
		return administratorMapper.enable(id);
	}

	/**
	 * 禁用
	 */
	public Integer disable(Long id) {
		if(id == null || id < 1) {
			return 0;
		}
		return administratorMapper.disable(id);
	}

	/**
	 * 重置密码为 888888
	 */
	public Integer reset(Long id) {
		if(id == null || id < 1) {
			return 0;
		}
		return administratorMapper.passwd(id, "888888");
	}

}
